#include "mycanvas.h"

MyCanvas::MyCanvas(QWidget *parent) :
    QWidget(parent)
{
    setAcceptDrops(true);
    setMinimumSize(400, 400);
    setMaximumSize(400, 400);
}

void MyCanvas::clear()
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    pieces.clear();
    update();
}

void MyCanvas::dragEnterEvent(QDragEnterEvent *event)
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    event->accept();
}

void MyCanvas::dragLeaveEvent(QDragLeaveEvent *event)
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    event->accept();
}

void MyCanvas::dragMoveEvent(QDragMoveEvent *event)
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    event->setDropAction(Qt::CopyAction);
    event->accept();
}

void MyCanvas::dropEvent(QDropEvent *event)
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    QByteArray pieceData = event->mimeData()->data(IconWidget::puzzleMimeType());
    QDataStream dataStream(&pieceData, QIODevice::ReadOnly);
    Piece piece;
    piece.rect = targetSquare(event->pos());
    dataStream >> piece.pixmap;

    pieces.append(piece);

    update(piece.rect);

    event->setDropAction(Qt::CopyAction);
    event->accept();
}

int MyCanvas::findPiece(const QRect &pieceRect) const
{
    for (int i = 0, size = pieces.size(); i < size; ++i) {
        if (pieces.at(i).rect == pieceRect)
            return i;
    }
    return -1;
}

void MyCanvas::mousePressEvent(QMouseEvent *event)
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    QRect square = targetSquare(event->pos());
    const int found = findPiece(square);

    if (found == -1)
        return;

    Piece piece = pieces.takeAt(found);

    update(square);

    QByteArray itemData;
    QDataStream dataStream(&itemData, QIODevice::WriteOnly);

    dataStream << piece.pixmap;

    QMimeData *mimeData = new QMimeData;
    mimeData->setData(IconWidget::puzzleMimeType(), itemData);

    QDrag *drag = new QDrag(this);
    drag->setMimeData(mimeData);
    drag->setHotSpot(event->pos() - square.topLeft());
    drag->setPixmap(piece.pixmap);

    if (drag->exec(Qt::CopyAction) != Qt::CopyAction) {
        pieces.insert(found, piece);
        update(targetSquare(event->pos()));
    }
}

void MyCanvas::paintEvent(QPaintEvent *event)
{
    qDebug() << __FILE__ << "," << __FUNCTION__ ;
    QPainter painter(this);
    painter.fillRect(event->rect(), Qt::white);

    for (const Piece &piece : pieces)
        painter.drawPixmap(piece.rect, piece.pixmap);
}

const QRect MyCanvas::targetSquare(const QPoint &position) const
{
    return QRect(position / 80 * 80, QSize(80, 80));
}
